<?php
use system\core\Config;
use system\core\Registry;

// form_open()
if ( ! function_exists('form_open') )
{
    /**
     * Returns a well formed form start tag
     * 
     * @param string $action
     * @return string
     */
    function form_open( $action = '', $method = 'post' )
    {
        if ( ! preg_match('#^https?://#i', $action) )
        {
            $baseUrl = Config::get('config', 'base_url');
        }
        else
        {
            $baseUrl = '';
        }

        return '<form action="' . $baseUrl . $action . '" method="' . $method . '" accept-charset="utf-8">' . PHP_EOL;
    }
}

// form_close()
if ( ! function_exists('form_close') )
{
    /**
     * Returns a closing form tag
     *  
     * @return string
     */
    function form_close()
    {
        return '</form>' . PHP_EOL;
    }
}

// set_value()
if ( ! function_exists('set_value') )
{
    /**
     * Set the value for form elements
     * 
     * @param string $name
     * @param string $default
     * @return string
     */
    function set_value( $name, $default = '' )
    {
        if ( isset($_REQUEST[$name]) )
        {
            return $_REQUEST[$name];
        }
        return $default;
    }
}

// validation_errors()
if ( ! function_exists('validation_errors') )
{
    /**
     * Get all validation errors
     */
    function validation_errors( $group = 'default', $prefix = '<p>', $suffix = '</p>' )
    {
        $output = '';
        
        $errors = Registry::get('form_validation_errors');
        
        if ( isset($errors[$group]) && count($errors[$group]) > 0 )
        {
            $output .= $prefix;
            foreach ( $errors[$group] as $error )
            {
                $output .= $error . '<br />' . PHP_EOL;
            }
            $output .= $suffix;
        }
        
        return $output;
    }
}

// validation_errors()
if ( ! function_exists('form_error') )
{
    /**
     * Get all validation errors
     */
    function form_error( $field, $group = 'default' )
    {
        $errors = Registry::get('form_validation_errors');
        
        if ( isset($errors[$group][$field]) && count($errors[$group][$field]) > 0 )
        {
            return '<span class="g-form-error">' . $errors[$group][$field] . '</span>';
        }
    }
}